package com.example.s.Activity.login;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.s.Activity.BaseActivity;
import com.example.s.R;
import com.example.s.network.OnMyNetworkListener;
import com.example.s.utils.LiveDataBus;
import com.example.s.utils.MyUtils;

import org.json.JSONObject;

import java.util.HashMap;

public class RegisterActivity extends BaseActivity {
    private ImageView back;
    private EditText userName;
    private EditText email;
    private EditText identifyCode;
    private TextView getIdentifyCode;
    private EditText password;
    private EditText confirmPassword;
    private ImageView seePwd;
    private TextView register;
    private TextView jumpLogin;
    private int codeLimitTime = 60;
    private Handler mHandler;
    boolean isSee = false;
    private int codeId;
    private final boolean[] isFinished = new boolean[5];

    private void initView() {

        back = (ImageView) findViewById(R.id.back);
        userName = (EditText) findViewById(R.id.userName);
        email = (EditText) findViewById(R.id.email);
        identifyCode = (EditText) findViewById(R.id.identifyCode);
        getIdentifyCode = (TextView) findViewById(R.id.getIdentifyCode);
        password = (EditText) findViewById(R.id.password);
        confirmPassword = (EditText) findViewById(R.id.confirmPassword);
        seePwd = (ImageView) findViewById(R.id.seePwd);
        register = (TextView) findViewById(R.id.register);
        jumpLogin = (TextView) findViewById(R.id.jumpLogin);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();

        register.setBackgroundResource(R.drawable.login_btn_unable_bg);
        LiveDataBus.getInstance().with("registerIsFinished", boolean[].class).setValue(isFinished);
        LiveDataBus.getInstance().with("registerIsFinished", boolean[].class).observe(this, new Observer<boolean[]>() {
            @Override
            public void onChanged(boolean[] booleans) {
                Log.d(TAG, "onChanged: ");
                for (boolean aBoolean : booleans) {
                    if (!aBoolean) {
                        register.setBackgroundResource(R.drawable.login_btn_unable_bg);
                        return;
                    }
                }
                register.setBackgroundResource(R.drawable.login_btn_bg);

            }
        });
        mHandler = new Handler(Looper.getMainLooper());
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        getIdentifyCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (MyUtils.getInstance().isHasEmpty(email.getText().toString())) {
                    Toast.makeText(A, "请输入邮箱！", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, Object> map = getMap();
                map.put("email", email.getText().toString());
                N.post("/api/code", map, new OnMyNetworkListener() {
                    @Override
                    public void success(JSONObject response) {
                        mHandler.post(mGetCodeTask);
                        getIdentifyCode.setEnabled(false);
                        Toast.makeText(A, "已经发送验证码！", Toast.LENGTH_SHORT).show();
                        codeId = response.optJSONObject("data").optInt("codeId");
                    }

                    @Override
                    public void fail(JSONObject response) {
                        Toast.makeText(A, "发送验证码失败，请检查邮箱！", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
        userName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                isFinished[0] = editable.length() != 0;
                LiveDataBus.getInstance().with("registerIsFinished", boolean[].class).setValue(isFinished);
            }
        }); //0

        email.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isFinished[1] = s.length() != 0;
                LiveDataBus.getInstance().with("registerIsFinished", boolean[].class).setValue(isFinished);
            }
        }); //1

        identifyCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

                isFinished[2] = editable.length() != 0;
                LiveDataBus.getInstance().with("registerIsFinished", boolean[].class).setValue(isFinished);
            }
        }); //2
        password.addTextChangedListener(new TextWatcher() {  //3
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                isFinished[3] = editable.length() != 0;
                LiveDataBus.getInstance().with("registerIsFinished", boolean[].class).setValue(isFinished);
            }
        }); //3
        confirmPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                isFinished[4] = s.length() != 0;
                seePwd.setVisibility(s.length() != 0 ? View.VISIBLE : View.INVISIBLE);
                LiveDataBus.getInstance().with("registerIsFinished", boolean[].class).setValue(isFinished);
            }
        }); //4

        seePwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "onClick: " + isSee);
                if (!isSee) {
                    password.setTransformationMethod(HideReturnsTransformationMethod
                            .getInstance());
                    confirmPassword.setTransformationMethod(HideReturnsTransformationMethod
                            .getInstance());  //密码以明文显示
                    v.setBackgroundResource(R.mipmap.eye_icon_close);
                    isSee = true;
                } else {
                    password.setTransformationMethod(PasswordTransformationMethod
                            .getInstance());
                    confirmPassword.setTransformationMethod(PasswordTransformationMethod
                            .getInstance());  //以密文显示，以.代替
                    v.setBackgroundResource(R.mipmap.eye_icon);
                    isSee = false;
                }
            }
        });
        jumpLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
            }
        });

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (MyUtils.getInstance().isHasEmpty(
                        userName.getText().toString().trim(),
                        email.getText().toString().trim(),
                        identifyCode.getText().toString().trim(),
                        password.getText().toString().trim(),
                        confirmPassword.getText().toString().trim()
                )) {
                    Toast.makeText(A, "请输入完整内容！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!password.getText().toString().trim().equals(confirmPassword.getText().toString().trim())) {
                    Toast.makeText(A, "两次密码输入不一致！", Toast.LENGTH_SHORT).show();
                    return;
                }
                HashMap<String, Object> map = getMap();
                map.put("account", userName.getText().toString().trim());
                map.put("nickName", userName.getText().toString().trim());
                map.put("password", password.getText().toString().trim());
                map.put("email", email.getText().toString().trim());
                map.put("code", identifyCode.getText().toString().trim());
                map.put("codeId", codeId);
                N.post("/api/register", map, new OnMyNetworkListener() {
                    @Override
                    public void success(JSONObject response) {
                        Toast.makeText(A, "注册成功", Toast.LENGTH_SHORT).show();
                        startActivity(LoginActivity.class);
                    }

                    @Override
                    public void fail(JSONObject response) {
                        Toast.makeText(A, response.optString("data"), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    private Runnable mGetCodeTask = new Runnable() {
        @Override
        public void run() {
            if (codeLimitTime <= 0) {
                mHandler.removeCallbacks(mGetCodeTask);
                getIdentifyCode.setText("获取验证码");
                getIdentifyCode.setEnabled(true);
                codeLimitTime = 60;
                return;
            }
            getIdentifyCode.setText(--codeLimitTime + "s");
            mHandler.postDelayed(mGetCodeTask, 1000);
        }
    };

}
